<template>
  <div class="article-list">
    <van-pull-refresh v-model="isLoading" :success-text="text" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败,点击重新加载"
        @load="onLoad"
      >
        <!-- <van-cell
          v-for="(article, index) in list"
          :key="index"
          :title="article.title"
        /> -->
        <articleItem v-for="(article, index) in list" :key="index" :article="article"></articleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from "@/api/login.js";
import articleItem from '@/views/home/component/article-item/index.vue'
export default {
  name: "articleList",
  components:{
    articleItem
  },
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      error: false,
      isLoading: false, //控制加载是否完成
      text:'刷新成功'
    };
  },
  methods: {
    async onRefresh() {
      try {
        // 1.请求数据
        const { data } = await getArticleList({
          channel_id: this.channel.id, // 频道 id
          timestamp: Date.now(), // 下拉刷新每次都应该获取最新数据
          with_top: 1, // 是否包含置顶，进入页面第一次请求时要包含置顶文章，1-包含置顶，0-不包含
        })
        // 2.将数据加载到顶部
        let { results } = data.data
        this.list.unshift(...results)
        // 3.关闭下拉刷新loading状态
        this.isLoading = false
        // 提示成功
        this.text = `刷新成功,更新了${results.length}条数据`
      } catch (err) {
        this.isLoading = false //关闭下拉刷新loading状态
        this.$toast('刷新失败')
      }
    },
    async onLoad() {
      try {
        const { data } = await getArticleList({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1,
        });
        const { results } = data.data;
        this.list.push(...results);
        // 设置本次加载中loading状态结束
        this.loading = false;
        // 判断是否加载结束,如果说有数据,说明还需要加载
        if (results.length) {
          this.timestamp = data.data.pre_timestamp;
        } else {
          // 没有数据了,设置加载状态结束,不在触发上拉加载更多
          this.finished = true;
        }
      } catch (err) {
        this.$toast("获取数据失败", err);
        this.loading = false; //关闭loading的效果
        this.error = true; //开启错误提示
      }
    },
  },
};
</script>

<style scoped lang="less">
.article-list{
  height: 79vh;
  overflow-y: auto;
}
</style>